#! /bin/sh

set -e

if [ "$1" = "configure" ]; then

  . /etc/zm/zm.conf
  for i in /etc/zm/conf.d/*.conf; do
    . $i
  done;


  # The logs can contain passwords, etc... so by setting group root, only www-data can read them, not people in the www-data group
  chown www-data:root /var/log/zm
  chown www-data:www-data /var/lib/zm
  if [ -z "$2" ]; then
    chown www-data:www-data /var/cache/zoneminder /var/cache/zoneminder/*
  fi

  # Do this every time the package is installed or upgraded
  # Ensure zoneminder is stopped
  invoke-rc.d zoneminder stop || true

  if [ "$ZM_DB_HOST" = "localhost" ]; then
    if [ -e "/etc/init.d/mysql" ]; then 
      #
      # Get mysql started if it isn't
      #
      if ! $(/etc/init.d/mysql status >/dev/null 2>&1); then
        invoke-rc.d mysql start
      fi
      if $(/etc/init.d/mysql status >/dev/null 2>&1); then
        mysqladmin --defaults-file=/etc/mysql/debian.cnf -f reload
        # test if database if already present...
        if ! $(echo quit | mysql --defaults-file=/etc/mysql/debian.cnf zm > /dev/null 2> /dev/null) ; then
          cat /usr/share/zoneminder/db/zm_create.sql | mysql --defaults-file=/etc/mysql/debian.cnf
          if [ $? -ne 0 ]; then
            echo "Error creating db."
            exit 1;
          fi
          # This creates the user.
          echo "grant lock tables, alter,drop,select,insert,update,delete,create,index,alter routine,create routine, trigger,execute, REFERENCES on ${ZM_DB_NAME}.* to '${ZM_DB_USER}'@localhost identified by \"${ZM_DB_PASS}\";" | mysql --defaults-file=/etc/mysql/debian.cnf mysql
        else
          echo "grant lock tables, alter,drop,select,insert,update,delete,create,index,alter routine,create routine, trigger,execute, REFERENCES on ${ZM_DB_NAME}.* to '${ZM_DB_USER}'@localhost;" | mysql --defaults-file=/etc/mysql/debian.cnf mysql
        fi

        zmupdate.pl --nointeractive
        zmupdate.pl --nointeractive -f

        # Add any new PTZ control configurations to the database (will not overwrite)
        zmcamtool.pl --import >/dev/null 2>&1

      else
        echo 'NOTE: mysql not running, please start mysql and run dpkg-reconfigure zoneminder when it is running.'
      fi
    else 
      echo 'mysql not found, assuming remote server.'
    fi
  else 
    echo "Not doing database upgrade due to remote db server ($ZM_DB_HOST)"
  fi
  echo "Done Updating, starting ZoneMinder"
  invoke-rc.d zoneminder start || true
fi

#DEBHELPER#
